'''
Created on Nov 7, 2011

@author: Bootup Baltimore
'''
import sys
import ScannerControl.ScannerFunctions as SF
import CameraControl.CameraFunctions as CF
import Gado.ComputerVision.BarcodeDetection as B
platform = sys.platform

import Robot
import time
if platform == "win32":
    import twain
    from Gado.TwainControl import TwainBase
    import Tkinter
import Gado.Database.Database as DB
import Gado.Database.DbFunctions as DBF

import os

import sane

if platform == "linux2":
    gado = Robot.Robot('/dev/ttyACM0')
else:
    gado = Robot.Robot('COM4')
time.sleep(5)
gado.connect()
conn = DB.databaseGetConn()

def newFolderPrompt(cursor):
    #Need to grab the last ~10 or so folders from the database
    #give the user a prompt to select between them and also the ability
    #to create a new folder
    
    #Once selected, the location_id needs to be updated so that all
    #future operations will correspond to the correct location
    
    #This will ensure consistent image naming
    locationPresent = 0
    folderHash = DBF.getRecentFolders(cursor)
    
    while locationPresent == 0:
        for folder in folderHash:
            print "Location_ID: %s, room: %s, case_number: %s, shelf_number: %s, box_number: %s, folder_name: %s" % (folder['location_id'], folder['room'], folder['case_num'], folder['shelf_num'], folder['box_num'], folder['folder_name'])
        
        location_id = raw_input("Please enter the number of the folder you would like you use\nIf you would like to create a new folder, enter '-1': ")
        print "LOCATION ID: %s" % location_id
        
        for folder in folderHash:
            if int(folder['location_id']) == int(location_id) or int(location_id) == -1:
                locationPresent = 1
    
    #Have a valid location_id or -1 (indicates a new folder)
    if int(location_id) == -1:
        con = 0
        while con == 0:
            #prompt for necessary fields
            room = raw_input("Please enter the folder's room: ")
            caseNum = raw_input("Please enter the folder's case number: ")
            shelfNum = raw_input("Please enter the folder's shelf number: ")
            boxNum = raw_input("Please enter the folder's box number: ")
            folderName = raw_input("Please enter the folder's name: ")
            
            con = raw_input("Does this look right?\nRoom: %s, case_number: %s, shelf_number: %s, box_number: %s, folder_name: %s\n 1-Yes, 0-No" % (room, caseNum, shelfNum, boxNum, folderName))
        
        location_id = DBF.createNewFolder(conn, cursor, room, caseNum, shelfNum, boxNum, folderName)
        print "Set a new location id of: " + str(location_id)
        conn.commit()
    return location_id

print "\a"
#Configuration
location_id = 0
cursor = DB.getCursorFromConn(conn)
location_id = newFolderPrompt(cursor)
user_id = 1
scanner_id = 3

if not platform == "linux2":
    F=Tkinter.Frame()
    window = F.winfo_id()


CF.captureAndDownloadImageLinux("output.jpg")
gado.goHome()
first_run = 1
while(1):
    #0
    name = time.time()
    if first_run == 0:
        CF.captureAndDownloadImageLinux("output.jpg")
    else:
        first_run = 0
    barcodes = B.findBarcodes("output.jpg")
    if barcodes:
        if barcodes[0] and barcodes[0] == "QH73372":
            gado.sendRawActuatorWithBlocking(25)
            print "--------"
            print "DONE WITH STACK"
            print "--------"
            exit()
    #1
    gado.sendRawArmTimeBlocking(20)
    start = time.time()
    
    #2
    gado.sendVacuum(255)
    gado.lowerAndLiftInternal()
    light_at_artifact = gado.data.light_value
    print light_at_artifact
    gado.sendRawActuatorWithBlocking(25)
    gado.sendRawActuatorWithBlocking(25)
    
    #3
    gado.sendRawArmTimeBlocking(100)
    
    #4
    gado.connect()
    print abs(int(gado.data.light_value) - int(light_at_artifact))
    if abs(int(gado.data.light_value) - int(light_at_artifact)) > 120:
        print "---"
        print "Possible image drop"
        print "---"
        exit()
    print gado.data.light_value
    gado.sendRawActuatorWithBlocking(110)
    
    #5
    conn.ping(True)
    returned_stuff = SF.scanImageLinux(conn, location_id, user_id, scanner_id)
    artifact_id = returned_stuff[0]
    next_i = returned_stuff[1]
    if not os.path.exists("output.jpg"):
        print "The camera failed to take an image"
        gado.sendRawActuatorWithBlocking(25)
        exit()
    cursor = DB.getCursorFromConn(conn)
    base_name = DBF.getBaseNameForLocation(cursor, location_id)
    name = "%s_%sa" % (base_name, next_i)
    image_name = "%s.jpg" % name
    #raw_path = "G:\\raw_scans\\%s" % image_name
    raw_path = "%s" % image_name
    #print raw_path
    os.rename('output.jpg', raw_path)
    DBF.addImageToArtifact(conn, cursor, artifact_id, name, raw_path, scanner_id, '2', user_id)
    #6
    gado.sendRawActuatorWithBlocking(70)
    
    #7
    gado.sendRawArmTimeBlocking(180)
    gado.sendVacuum(0)
    time.sleep(2)
    elapsed = time.time() - start
    elapsed = elapsed - 5
    print elapsed



